package com.liao.myblog.controller.admin;

import com.liao.myblog.enums.ResultCode;
import com.liao.myblog.pojo.Catalogue;
import com.liao.myblog.service.CatalogueService;
import com.liao.myblog.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping(value = "/admin")
@Controller
public class CategoryController {

    @Resource
    private CatalogueService catalogueService;

    @RequestMapping(value = "/categories")
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "categories");
        return "/admin/category";
    }

    @ResponseBody
    @GetMapping(value = "/catalogue/list")
    private List<Catalogue> catalogue() {
        List<Catalogue> catalogueList = catalogueService.findCatalogueList();
        System.out.println(catalogueList);
        return catalogueList;
    }

    @ResponseBody
    @PostMapping(value = "/catalogue/update")
    public ResultVO<Object> updateCatalogue(@RequestBody Catalogue catalogue) {
        catalogue.setTime(new Date());
        catalogue.setIsDelete((byte) 0);
        int i = catalogueService.updateCatalogue(catalogue);
        if (i < 1) {
            return new ResultVO<>(ResultCode.ERROR);
        }
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @ResponseBody
    @PostMapping(value = "/catalogue/save")
    public ResultVO<Object> saveCatalogue(@RequestBody Catalogue catalogue) {
        catalogue.setIsDelete((byte) 0);
        catalogue.setTime(new Date());
        int i = catalogueService.addCatalogue(catalogue);
        if (i < 1) {
            return new ResultVO<>(ResultCode.ERROR);
        }
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @ResponseBody
    @PostMapping(value = "/catalogue/delete")
    public ResultVO<Object> deleteCatalogue(@RequestBody Map<String,int[]> ids) {
        int i = catalogueService.deleteCatalogue(ids.get("ids"));
        if (i < 1) {
            return new ResultVO<>(ResultCode.ERROR);
        }
        return new ResultVO<>(ResultCode.SUCCESS);
    }
}
